package dataextraction;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ACMEngineLoader extends AbstractEngineLoader{

	private static final String ACM_PUBLISHER = "ACM";

	private static ACMEngineLoader instance;
	
	private static int NUM_OF_ENTRIES = 1; 
		
	public static ACMEngineLoader getInstance() {
		if (ACMEngineLoader.instance == null) {
			ACMEngineLoader.instance = new ACMEngineLoader();
		}
		return ACMEngineLoader.instance;
	}
	
	private ACMEngineLoader() {
		
	}

	
	private List<Entry> createEntries(String document){
		Pattern patternURL = Pattern.compile("<A HREF=\".*?\""); 
	    
	    Matcher matcherURL = patternURL.matcher(document);
	    
	    Pattern patternTitle = Pattern.compile("\"_self\">.*?</A>"); 
	    
	    Matcher matcherTitle = patternTitle.matcher(document);
	   
	    ArrayList<Entry> entries = new ArrayList<Entry>();
	       
	   
	    //ArrayList<String> fields = new ArrayList<String>();
	    
	    while (matcherURL.find() && matcherTitle.find()) {
	    	
	    	 Entry entry = new Entry();
	    	
	    	String url = matcherURL.group();
	    	entry.setPdfLink("http://dl.acm.org/"+url.substring(9,url.length()-1));  
	    	
	    	String title = matcherTitle.group();
	    	entry.setDocumentTitle(title.substring(8,title.length()-4));
	    	entry.setPublisher(ACM_PUBLISHER);
	    	entry.setId("A_"+ACM_PUBLISHER+"_"+NUM_OF_ENTRIES++);
	    	entry.setPublicationAbstract("N/A");
	    	
	    	entries.add(entry);
	    }
	  
	    return entries;
	}
	
	
	public List<Entry> reader(File csvFile) throws IOException {

		FileInputStream stream = new FileInputStream(csvFile);  
        InputStreamReader streamReader = new InputStreamReader(stream);  
        BufferedReader reader  = new BufferedReader(streamReader);
        
        List<Entry> entriesOnFile = new ArrayList<Entry>();
        
        StringBuffer document = new StringBuffer();

        String line = null;
               
        while ((line = reader.readLine()) != null) {  
        	document.append(line);
            
        }  
        
        entriesOnFile = createEntries(document.toString());
                
        reader.close();
        streamReader.close();
        stream.close();
		
        
        System.out.println("Fim do arquivo "+ csvFile.getName() + " # de entradas: "+entriesOnFile.size());
       
        
        return entriesOnFile;
	}

	@Override
	protected String getPublisher() {
		return ACM_PUBLISHER;
	}
	
}
